package com.plugin.timesdk.timesdk_plugin;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.kk.sdkforzip.SdkForZipUtils;

import org.json.JSONObject;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import java.util.Map;
import java.util.HashMap;
import java.io.File;

/** TimesdkPlugin */
public class TimesdkPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private Context mContext;
  private Activity mActivity;
  private MethodChannel channel;
  private SdkForZipUtils mSdkForZipUtils;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "timesdk_plugin");
    channel.setMethodCallHandler(this);
    mContext = flutterPluginBinding.getApplicationContext();

  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if(call.method.equals("initTimeSDK")) {
      initTimeSDK(call, result);
    } else if(call.method.equals("collectMessage")) {
      Map json = call.argument("data");
      collectMessage(json, call, result);
    } else if(call.method.equals("checkSdkPermission")) {
      requestPermission(call, result);
    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }

  @Override
  public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
    mActivity = binding.getActivity();
  }

  @Override
  public void onDetachedFromActivityForConfigChanges() {

  }

  @Override
  public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
    onAttachedToActivity(binding);
  }

  @Override
  public void onDetachedFromActivity() {

  }

  private void initTimeSDK(MethodCall call, Result result) {
    System.out.println("============ initTimeSDK ===========");

    mSdkForZipUtils = new SdkForZipUtils(mActivity, new SdkForZipUtils.OnTimeFileCallBack() {

      @Override
      public void onFile(File file, String md5, String orderNo, boolean isSubmit, String json) {
        // 获取到文件，执行上传逻辑
//        up6In1(file, md5, orderNo,isSubmit, 0);

        Map<String, Object> map = new HashMap();
        map.put("file", file.getAbsoluteFile());
        map.put("md5", md5);
        map.put("orderNo", orderNo);
        map.put("isSubmit", isSubmit);
        map.put("count", 0);
        channel.invokeMethod("upload_success", map);
      }

      @Override
      public void onFail(String orderNo, boolean isSubmit, String json) {

        Map<String, Object> map = new HashMap();
        map.put("orderNo", orderNo);
        map.put("isSubmit", isSubmit);
        channel.invokeMethod("upload_fail", map);
      }
    });

    if (mSdkForZipUtils == null) {
      result.error("", "sdk init fail", null);
    }

  }

  private void collectMessage(Map json, MethodCall call, Result result) {
    System.out.println("============" + json + "=======");
    if (mSdkForZipUtils != null) {
      mSdkForZipUtils.setJson(new Gson().toJson(json));
    } else {
      result.error("", "sdk is not init", null);
    }

  }

  private void requestPermission(MethodCall call, Result result) {
    if (mSdkForZipUtils != null) {
        // 获取权限
        // 权限回调结果需要在项目MainActivity下重写onRequestPermissionsResult
        mSdkForZipUtils.onRequestPermission();
        Log.i("", "mSdkForZipUtils 获取权限");
    } else {
      Log.i("", "mSdkForZipUtils is null");
      result.error("", "SDK is not init", "");
    }
  }

  public int getTimeRequestCode() {
    return SdkForZipUtils.TIME_PERMISSION_REQUEST_CODE;
  }

//      @Override
//      public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == SdkForZipUtils.TIME_PERMISSION_REQUEST_CODE) {
//
//          // mTimeManager 获取权限
//          mSdkForZipUtils.onRequestPermission();
//
//          if (SdkForZipUtils.mIsSubmit) {
//            // toast 权限问题
////            boolean isNever = false;
////            for (String s : permissions) {
////              if (s.equals(Manifest.permission.READ_PHONE_STATE) && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED && !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE))
////                isNever = true;
////              if (s.equals(Manifest.permission.READ_SMS) && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_SMS))
////                isNever = true;
////              if (s.equals(Manifest.permission.READ_CONTACTS) && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED && !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS))
////                isNever = true;
////              if (s.equals(Manifest.permission.READ_EXTERNAL_STORAGE) && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE))
////                isNever = true;
////            }
////            if (isNever)
////              toast("Autorice los permisos antes de entregar la solicitud");
////          }
////
////        }
////
//      }
//
//    });
//
//  }


}
